package com.bolt.admin.module.controller;

import com.bolt.admin.config.RsaProperties;
import com.bolt.admin.module.sys.dto.LoginReqDTO;
import com.bolt.admin.module.sys.service.OnlineUserService;
import com.bolt.admin.module.sys.service.UserService;
import com.bolt.admin.security.shiro.AuthContextHolder;
import com.bolt.admin.security.shiro.AuthUserDetails;
import com.bolt.admin.security.shiro.jwt.UserInfo;
import com.bolt.common.BoltConstants;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.convention.data.code.AuthCode;
import com.bolt.support.captcha.CaptchaExceptionEnum;
import com.bolt.support.captcha.CaptchaService;
import com.bolt.support.captcha.CaptchaVO;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController()
@Api(description = "登录相关")
@RequiredArgsConstructor
public class AdminController {

    private final UserService userService;

    private final OnlineUserService onlineUserService;

    private final CaptchaService captchaService;

    @ResponseBody
    @RequestMapping(value = "/auth/captcha/graph")
    public ResultMessage<CaptchaVO> captchaGraph(CaptchaVO captchaVO) {
        CaptchaVO data = captchaService.get(captchaVO);
        return Results.success(data);
    }

    @ResponseBody
    @PostMapping(value = "/auth/captcha/check")
    public ResultMessage check(@RequestBody CaptchaVO captchaVO) {
        captchaVO.setSecretKey(RsaProperties.privateKey);
        boolean success = captchaService.check(captchaVO);
        return success ? Results.success() : Results.failure(CaptchaExceptionEnum.AUTH_CAPTCHA_VERIFY_ERROR);
    }

    @PostMapping("/auth/login")
    public ResultMessage<Map<String, String>> Login(LoginReqDTO loginReqDTO) throws Exception {
        String jwt = userService.login(loginReqDTO);
        Map<String, String> token = new HashMap<>();
        token.put("access_token", jwt);
        return Results.success(token);
    }

    @GetMapping("/api/userInfo")
    public ResultMessage<UserInfo> userInfo() {
        AuthUserDetails userDetails = AuthContextHolder.getAuthUserDetails();
        UserInfo userInfo = userService.userInfo(userDetails.getUserId());
        return Results.success(userInfo);
    }

    @DeleteMapping("/auth/logout")
    public ResultMessage logout(@RequestHeader HttpHeaders headers) {
        if (headers.containsKey(BoltConstants.AUTH_HEADER)) {
            String key = headers.get(BoltConstants.AUTH_HEADER).get(0);
            onlineUserService.logOut(key);
            return Results.success();
        } else {
            return Results.failure(AuthCode.MISSING_ACCESS_TOKEN);
        }
    }
}

 